<!--
 * @Author: liujinjun681 liujinjun681@qq.com
 * @Date: 2022-09-08 16:04:23
 * @LastEditors: liujinjun681 liujinjun681@qq.com
 * @LastEditTime: 2022-10-09 16:15:32
 * @FilePath: \hd_ims_web\src\views\output\outputData\qrCode\index.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
  <div class="app-container" @click="focusInp">
    <input
      id="inpRrqId"
      type="text"
      v-model="form.rrqId"
      autofocus="autofocus"
      @keyup.enter="scanQr"
      style="height: 0px; width: 0px; border: none; opacity: 0"
    />
    <el-row :gutter="20">
      <el-col :span="8">
        <el-card>
          <div slot="header">
            <span>出库操作台</span>
            <el-button
              style="float: right; padding: 3px 0"
              type="text"
              @click="clearALL"
              >重新开始扫码</el-button
            >
          </div>

          <div style="font-size: 18px; color: magenta">
            当前已扫码识别{{ num }}次，成功{{ numSuccess }}次!
          </div>
          <ol
            class="ollist"
            element-loading-text="扫码识别中..."
            element-loading-spinner="el-icon-loading"
            v-loading="loading || !this.num"
          >
            <li>开单日期：{{ $moment(itemCur.rrqRq).format("YYYY-MM-DD") }}</li>
            <li>班次：{{ itemCur.rrqBc }}</li>
            <li>品名规格：{{ itemCur.itmPmgg }}</li>
            <li>客户代码：{{ itemCur.itmCustwldm }}</li>
            <li>出库数量：{{ itemCur.rrqNumber }}</li>
            <li>箱号：{{ itemCur.rrqXs }}</li>
          </ol>
        </el-card>
      </el-col>
      <el-col :span="16">
        <el-card>
          <div slot="header">
            <span>扫码出库信息</span>
          </div>
          <div class="scrollbarQr" id="printContent">
            <el-table :data="listQr" stripe>
              <el-table-column
                label="品名规格"
                prop="itmPmgg"
                min-width="200px"
              />
              <el-table-column
                label="客户代码"
                prop="itmCustwldm"
                width="120px"
              />
              <el-table-column label="生产日期" prop="rrqRq" width="100px">
                <template #default="scope">
                  {{ $moment(scope.row.rrqRq).format("YYYY-MM-DD") }}
                </template>
              </el-table-column>
              <el-table-column label="班次" prop="rrqBc" width="60px" />
              <el-table-column label="出库时间" prop="rrqRkTime" width="120px">
                <template #default="scope">
                  {{ $moment(scope.row.cldSmrq).format("YYYY-MM-DD HH:mm:ss") }}
                </template>
              </el-table-column>
              <el-table-column label="出库仓库" prop="itmCkdm" width="120px">
                <template #default="scope">
                  <dict-tag
                    :options="warehouse_list"
                    :value="scope.row.itmCkdm"
                  />
                </template>
              </el-table-column>
              <!-- <el-table-column label="可用数量" prop="rrqKysl" width="80px" /> -->
              <el-table-column label="数量" prop="rrqCur" width="80px" />
              <el-table-column label="箱号" prop="rrqXs" width="60px" />
            </el-table>
          </div>
        </el-card>
      </el-col>
    </el-row>
    <!-- 修改设备保养作业对话框 -->
    <el-dialog
      title="半成品扫码出库确认"
      v-model="openFix"
      :close-on-click-modal="false"
      draggable
      width="520px"
      append-to-body
    >
      <div class="formlarge">
        <el-form label-width="120px" ref="fixDialog">
          <el-form-item label="客户代码：" prop="itmCustwldm">
            <el-input disabled v-model="itemCur.itmCustwldm" />
          </el-form-item>
          <el-form-item label="品名规格：" prop="itmPmgg">
            <el-input disabled v-model="itemCur.itmPmgg" />
          </el-form-item>
          <el-form-item label="机台：" prop="jtbh" v-if="itemCur.list">
            <el-select
              v-model="itemCur.jtbh"
              @change="jtChange"
              value-key="moeJtbh"
            >
              <el-option
                v-for="item in itemCur.list"
                :key="item.moeJtbh"
                :label="item.moeJtbh"
                :value="item"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="父项代码：" v-if="itmMstrs">
            <el-select
              v-model="itemCur.parentItem"
              @change="
                (x) => {
                  Object.assign(itemCur, {
                    klsl: x.number,
                    parentItem: x.itmCustwldm,
                  });
                  $refs.fixDialog.$forceUpdate();
                }
              "
              value-key="itmCustwldm"
            >
              <el-option
                v-for="item in itmMstrs"
                :key="item.itmCustwldm"
                :label="item.itmCustwldm"
                :value="item"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="领料需求数：" v-if="itemCur.list">
            <input
              disabled
              v-model="itemCur.klsl"
              style="font-size: 16px; color: red"
            />
          </el-form-item>

          <el-form-item label="数量：" prop="rrqKysl">
            <el-input-number
              ref="rrqKysl"
              v-model="itemCur.rrqKysl"
              :max="itemCur.rrqNumber"
              :min="0"
              controls-position="right"
            ></el-input-number>
          </el-form-item>
        </el-form>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button @click="clearALL">取 消</el-button>
        <el-button type="primary" @click="save">确 定</el-button>
      </div>
    </el-dialog>
    <audio
      style="display: none"
      ref="audio"
      id="scan_success"
      src="@/assets/audio/scan_success.wav"
    ></audio>
    <audio
      style="display: none"
      ref="audiod"
      id="scan_fail"
      src="@/assets/audio/scan_fail.wav"
    ></audio>
    <audio
      style="display: none"
      ref="audiod"
      id="stocks_low"
      src="@/assets/audio/stocks_low.wav"
    ></audio>
    <audio
      style="display: none"
      ref="audiod"
      id="operation_fail"
      src="@/assets/audio/operation_fail.wav"
    ></audio>
  </div>
</template>

<script>
import { getAll } from "@/api/repertory/Storage";
import {
  halfOutOfStock,
  selectRrqDetByRrqId,
} from "@/api/repertory/putstorage";
import {
  automaticStorage,
  PDACusWldmList,
  getItmMstrByPDACustwldm,
  getStatisticsWarehousing,
} from "@/api/repertory/PDA";
speechSynthesis.getVoices();

export default {
  name: "OutWareQrHalf",
  data() {
    return {
      form: {
        rrqBc: null,
        rrqRq: null,
        rrqWldm: null,
        rrqNumber: 0,
        count: "",
        rrqId: "",
      },
      openFix: false,
      date: "",
      BcDm: "白班",
      customerCode: "",
      itemCur: {
        rrqNumber: undefined,
        rrqKysl: undefined,
        klsl: undefined,
        list: null,
        parentItem: undefined,
        jtbh: undefined,
      },
      pm: "",
      itmMstrs: null,
      listId: [],
      listQr: [],
      loading: false,
      num: 0,
      kysl: 0,
      numSuccess: 0,
      //提供的所有客户代码
      provider_list_data: [],
      //符合条件的客户代码
      provider_list: [],
      //出库仓库
      warehouse_list: [],
      //出库类型
      type_list: [],
      //出库客户
      kh_list: [],
    };
  },
  created() {
    //请求所有客户代码
    PDACusWldmList().then((response) => {
      this.provider_list_data = response.data;
    });

    //所有仓库
    getAll().then((response) => {
      this.warehouse_list = response.data.map((o) => {
        o.dictLabel = o.storageName;
        o.dictValue = "" + o.storageId;
        return o;
      });
    });
    document.addEventListener("keyup", this.handleKeyEvent);
  },
  beforeDestroy() {
    // 清理事件监听器
    document.removeEventListener("keyup", this.handleKeyEvent);
  },
  beforeRouteEnter(to, from, next) {
    next((vm) => {
      setTimeout(vm.focusInp, 300);
      setTimeout(vm.focusInp, 600);
      setTimeout(vm.focusInp, 900);
      // 通过 `vm` 访问组件实例
    });
  },
  mounted() {
    this.scan_success = document.getElementById("scan_success");
    this.scan_fail = document.getElementById("scan_fail");
    this.stocks_low = document.getElementById("stocks_low");
    this.operation_fail = document.getElementById("operation_fail");
  },
  methods: {
    handleKeyEvent(event) {
      // 检查按键是否为回车键
      if (event.key === "Enter") {
        // 这里处理回车事件
        console.log("全局回车事件被触发");
        if (this.openFix) {
          this.save();
          return;
        } else {
          this.focusInp();
        }
      }
    },
    speak(text) {
      if (window.speechSynthesis) {
        const voices = speechSynthesis.getVoices();
        const voice =
          voices.find(
            (o) => o.lang === "zh-CN" && o.name.includes("Xiaoxiao")
          ) || voices[0];
        console.log(voice);
        const utterance = new SpeechSynthesisUtterance();
        utterance.text = text;
        utterance.lang = "zh-CN";
        utterance.volume = 1;
        utterance.pitch = 0.8;
        utterance.rate = 1.25;
        utterance.voice = voice;
        speechSynthesis.speak(utterance);
      } else if (
        navigator.mediaDevices &&
        navigator.mediaDevices.getUserMedia
      ) {
        navigator.mediaDevices
          .getUserMedia({ audio: true })
          .then((stream) => {
            const audioDestination =
              audioContext.createMediaStreamDestination();
            const audioSource = audioContext.createMediaStreamSource(stream);
            const audio = new Audio(audioDestination.stream);
            audio.play();

            const synth = new window.SpeechSynthesisUtterance();
            synth.text = text;
            synth.lang = "zh-CN";
            synth.volume = 1;
            synth.rate = 1;
            window.speechSynthesis.speak(synth);
          })
          .catch((err) => {
            console.error("获取音频输出设备失败", err);
          });
      } else {
        console.error("浏览器不支持语音合成");
      }
    },
    msg(msg, type) {
      this.$message({ showClose: true, message: msg, type: "success" });
    },
    scanQr(id) {
      if (
        !this.form.rrqId ||
        this.form.rrqId.indexOf("2022-") == -1 ||
        this.loading
      ) {
        this.form.rrqId = "";
        return;
      }
      const tmpId = this.form.rrqId;
      //this.listId.push(tmpId)
      this.num++;
      this.loading = true;

      selectRrqDetByRrqId(tmpId, {
        type: this.lastId === tmpId ? "1" : null,
      }).then((res) => {
        //Object.assign(this.itemCur, res.data)
        this.itemCur = res.data;
        this.itemCur.tmpId = tmpId;
        this.loading = false;
        this.openFix = true;
        this.itmMstrs = null;
        setTimeout(() => {
          //console.log(this.$refs)
          this.$refs.rrqKysl.focus();
          this.$refs.rrqKysl.select();
        }, 300);
        // document.getElementById('inpRrqId').focus()
        // this.scan_success.play()
      });
      this.form.rrqId = "";
    },
    save() {
      if (!this.openFix) {
        return;
      }
      if (this.itemCur.list && !this.itemCur.jtbh) {
        this.msgError("请先选择机台！");
        return;
      }
      if (
        this.itmMstrs &&
        this.itmMstrs.length > 1 &&
        !this.itemCur.parentItem
      ) {
        this.msgError("请先选择父项代码！");
        return;
      }
      halfOutOfStock(this.itemCur.tmpId, this.itemCur.rrqKysl, {
        rrqJtbh: this.itemCur.jtbh,
        parentItem: this.itemCur.parentItem,
      })
        .then((res) => {
          const tmp = this.itemCur.rrqKysl;
          this.itemCur = res.data;
          this.itemCur.rrqCur = tmp;
          this.loading = false;
          this.listQr.unshift(res.data);
          this.listQr = this.listQr.slice(0, 30);
          this.numSuccess++;
          //setTimeout(() => {
          this.loading = false;
          //}, 500)
          this.focusInp();
          this.openFix = false;
          this.scan_success.play();
        })
        .catch((e) => {
          setTimeout(() => {
            this.loading = false;
          }, 500);
          console.log(e.message, e);
          if (e.message.indexOf("库存数量不足") > 0) {
            this.stocks_low.play();
            return;
          } else {
            if (window.speechSynthesis) {
              this.speak(e.message);
            } else {
              this.scan_fail.play();
            }
          }
          this.$notify.error({
            title: "错误",
            message: e.message,
            duration: 10000,
          });
        });
      this.form.rrqId = "";
    },
    focusInp() {
      document.getElementById("inpRrqId").focus();
      setTimeout(() => {
        document.getElementById("inpRrqId").focus();
      }, 100);
    },
    clearALL() {
      this.focusInp();
      this.loading = false;
      this.listQr = [];
      this.listId = [];
      this.num = 0;
      this.numSuccess = 0;
      this.itemCur = {};
      this.openFix = false;
    },
    getAllCustomer(queryString, cb) {
      if (this.customerCode == null || this.customerCode == "") {
        return;
      }
      let temp = [];
      this.clearALL();

      temp = this.provider_list_data
        .filter((i) => {
          return i.itmCustwldm.substr(-6).indexOf(this.customerCode) != -1;
        })
        .slice(0, 30);
      cb(temp);
    },
    FillAttribute() {
      if (this.customerCode == null || this.customerCode == "") {
        return;
      }

      getItmMstrByPDACustwldm({ itmCustwldm: this.customerCode }).then(
        (res) => {
          if (res.code == "200") {
            this.form.rrqWldm = res.data.itmWldm;
            this.pmgg = res.data.itmPmgg;
            this.rkkh = res.data.itmKhdm;
            this.rkck = res.data.itmCkdm;
            this.pm = res.data.itmWlpm;
            this.$Message.success("成功");
          } else {
            alert(res.msg);
          }
        }
      );
    },
    jtChange(r) {
      this.itemCur.jtbh = r.moeJtbh;
      if (r && r.itmMstrs) {
        if (r.itmMstrs.length > 1) {
          this.itmMstrs = r.itmMstrs;
          this.itemCur.klsl = undefined;
          this.itemCur.parentItem = undefined;
          this.$refs.fixDialog.$forceUpdate();
        } else {
          this.itmMstrs = null;
          this.itemCur.klsl = r.number;
          this.itemCur.parentItem = r.itmMstrs[0].itmCustwldm;
        }
      }
    },
  },
};
</script>
<style lang="scss" scoped>
.ollist {
  list-style-type: none;
  margin: 15px 0px;
  width: 200px;
}
.divqr {
  display: flex;
  page-break-inside: avoid;
}
.formlarge {
  ::v-deep .el-form-item__label {
    font-size: 18px !important;
  }
  ::v-deep .el-input {
    font-size: 18px;
  }
}
</style>
